/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
 * license.  See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */


/**
 * @requires OpenLayers/Layer/Markers.js
 * @requires OpenLayers/Ajax.js
 */

/**
 * Class: OpenLayers.Layer.GeoRDF
 * Add GeoRDF point features to your map. 
 * 
 * Inherits from:
 *  - <OpenLayers.Layer.Markers>
 *  - <OpenLayers.Layer>
 */

GeoRdfLayer = OpenLayers.Class(OpenLayers.Layer.Markers, {

    /** 
     * Property: location 
     * {String} store url of text file 
     */
    location: null,

    /** 
     * Property: features 
     * {Array(<OpenLayers.Feature>)} 
     */
    features: null,
    
    /**
     * APIProperty: formatOptions
     * {Object} Hash of options which should be passed to the format when it is
     * created. Must be passed in the constructor.
     */
    formatOptions: null, 

    /** 
     * Property: selectedFeature 
     * {<OpenLayers.Feature>} 
     */
    selectedFeature: null,

    /** 
     * APIProperty: icon 
     * {<OpenLayers.Icon>}. This determines the Icon to be used on the map
     * for this GeoRSS layer.
     */
    icon: null,

    /**
     * APIProperty: popupSize
     * {<OpenLayers.Size>} This determines the size of GeoRSS popups. If 
     * not provided, defaults to 250px by 120px. 
     */
    popupSize: null, 
    
    /** 
     * APIProperty: useFeedTitle 
     * {Boolean} Set layer.name to the first <title> element in the feed. Default is true. 
     */
    useFeedTitle: true,
    
    /**
    * Constructor: OpenLayers.Layer.GeoRSS
    * Create a GeoRSS Layer.
    *
    * Parameters:
    * name - {String} 
    * location - {String} 
    * options - {Object}
    */
    initialize: function(name, location, options) {
    	this.loaded=true;
        OpenLayers.Layer.Markers.prototype.initialize.apply(this, [name, options]);
       	this.previousLoadedBounds = map.getExtent();
       this.location="http://giv-heatmap.uni-muenster.de:8000/sparql?query=PREFIX+rdfs%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2000%2F01%2Frdf-schema%23%3E%0D%0APREFIX+geo%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2003%2F01%2Fgeo%2Fwgs84_pos%23%3E%0D%0APREFIX+xsd%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2001%2FXMLSchema%23%3E%0D%0APREFIX+rdf%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F1999%2F02%2F22-rdf-syntax-ns%23%3E%0D%0APREFIX+transit%3A+%3Chttp%3A%2F%2Fvocab.org%2Ftransit%2Fterms%2F%3E%0D%0APREFIX+dcterms%3A+%3Chttp%3A%2F%2Fpurl.org%2Fdc%2Fterms%2F%3E%0D%0APREFIX+ext%3A+%3Cjava%3Aorg.geospatialweb.arqext.%3E%0D%0ACONSTRUCT{%09%3Fa+rdf%3Atype+transit%3AStop.+%0D%0A%3Fa+rdfs%3Alabel+%3Flabel.%0D%0A%3Fa+geo%3Alat+%3Flat.%0D%0A%3Fa+geo%3Along+%3Flong.}%0D%0AFROM+%3Chttp%3A%2F%2Fgiv-heatmap.uni-muenster.de%2Fpt%2Fstations.rdf%3E%0D%0AWHERE+{%0D%0A%09%3Fa+ext%3Awithin%28$bottom$+$left$+$top$+$right$%29.%0D%0A%09%3Fa+rdf%3Atype+transit%3AStop.+%0D%0A%09%3Fa+rdfs%3Alabel+%3Flabel.%0D%0A%09%3Fa+geo%3Alat+%3Flat.%0D%0A%09%3Fa+geo%3Along+%3Flong.%0D%0A%0D%0A}%0D%0A%0D%0A&accept=text%2Fhtml";
        this.features = [];
        this.warningShown=false;
     },

    /**
     * Method: destroy 
     */
    destroy: function() {
        // Warning: Layer.Markers.destroy() must be called prior to calling
        // clearFeatures() here, otherwise we leak memory. Indeed, if
        // Layer.Markers.destroy() is called after clearFeatures(), it won't be
        // able to remove the marker image elements from the layer's div since
        // the markers will have been destroyed by clearFeatures().
        OpenLayers.Layer.Markers.prototype.destroy.apply(this, arguments);
        this.clearFeatures();
        this.features = null;
    },

    /**
     * Method: loadRDF
     * Start the load of the RDF data. Don't do this when we first add the layer,
     * since we may not be visible at any point, and it would therefore be a waste.
     */
    loadRDF: function(bounds) {				
      
      	if (this.visibility && this.loaded) {
      			
			//  if( this.map.getZoom()>13){
				
					var googleProjection = new OpenLayers.Projection("EPSG:900913");
				//display Projection
				var wgs84Projection = new OpenLayers.Projection("EPSG:4326");
				if(this.previousLoadedBounds!=bounds){
						this.events.triggerEvent("loadstart");
						box=bounds.transform(googleProjection,wgs84Projection);
						sparqlurl = this.location.replace("$left$",box.left).replace("$top$",box.top).replace("$bottom$",box.bottom).replace("$right$",box.right);
						OpenLayers.Request.GET({
							url: sparqlurl,
							success: this.parseData,
							scope: this
						});
						this.loaded=false;
						this.previousLoadedBounds=bounds;
				}

        	//} 
        
        }
    },    
    
    /**
     * Method: moveTo
     * If layer is visible and RSS has not been loaded, load RSS. 
     * 
     * Parameters:
     * bounds - {Object} 
     * zoomChanged - {Object} 
     * minor - {Object} 
     */
    moveTo:function(bounds, zoomChanged, minor) {
        OpenLayers.Layer.Markers.prototype.moveTo.apply(this, arguments);
    //    if(this.visibility && !this.loaded){
	if(this.visibility ){
       //    this.events.triggerEvent("loadstart");
        //    this.events.triggerEvent("moveend");
            this.loadRDF(bounds);
        }
    },
        
    /**
     * Method: parseData
     * Parse the data returned from the Events call.
     *
     * Parameters:
     * ajaxRequest - {<OpenLayers.Request.XMLHttpRequest>} 
     */
    parseData: function(ajaxRequest) {
			
        var doc = ajaxRequest.responseXML;
         
        if (!doc || !doc.documentElement) {
            doc = OpenLayers.Format.XML.prototype.read(ajaxRequest.responseText);
        }

       
        var options = {};
        
        OpenLayers.Util.extend(options, this.formatOptions);
        
        if (this.map && !this.projection.equals(this.map.getProjectionObject())) {
            options.externalProjection = this.projection;
            options.internalProjection = this.map.getProjectionObject();
        }    
        
        var format = new GeoRdfFormat(options);
        var features = format.read(doc);
        doc=0;
        
        for (var i = 0; i < features.length; i++) {
            var data = {};
            var feature = features[i];
            
            // we don't support features with no geometry in the GeoRSS
            // layer at this time. 
            if (!feature) {
                continue;
            }  
            if (!feature.geometry) {
                continue;
            }                      
              googleProjection = new OpenLayers.Projection("EPSG:900913");

	        wgs84Projection = new OpenLayers.Projection("EPSG:4326");
            var location = feature.geometry.getBounds().getCenterLonLat().transform(wgs84Projection,googleProjection) ;
            feature.geometry=feature.geometry.transform(wgs84Projection,googleProjection) ;    
        	data.icon = this.icon == null ? OpenLayers.Marker.defaultIcon() : this.icon.clone();	
			feature.layer=this;               
            feature.marker=new OpenLayers.Marker(new OpenLayers.LonLat(feature.geometry.x,feature.geometry.y),data.icon);

            this.features.push(feature);
            feature.marker.events.register('click', feature, this.markerClick);
            this.addMarker(feature.marker);
        }
        this.events.triggerEvent("loadend");
        this.loaded=true;
      
    },
    
    
    /**
     * Method: markerClick
     *
     * Parameters:
     * evt - {Event} 
     */
    markerClick: function(evt) {
        var sameMarkerClicked = (this == this.layer.selectedFeature);
        var data={};
        	feature=this;
                    var title = feature.attributes.title ? 
                         feature.attributes.title : "Untitled";
            
            var description = feature.attributes.description ? 
                         feature.attributes.description : "No description.";
                         
                         var nr = feature.attributes.nr;
            
            var link = feature.attributes.uri;
	
			var nodeID = feature.attributes.nodeID;
			            data.icon = this.icon == null ? 
                                     OpenLayers.Marker.defaultIcon() : 
                                     this.icon.clone();
                 
            data.popupSize = this.popupSize ? 
                             this.popupSize.clone() :
                             new OpenLayers.Size(250, 90);
            var contentHTML;
            if (title || description) {
                // we have supplemental data, store them.
                data.description = description;
				description = description.replace("<br> StopName: ","");
				// description = description.replace("<br>","");
				// description = description.substring(1,clickedMarkerDescription.length);
				
            
                contentHTML = '<div><div class="olLayerGeoRSSClose">[x]</div>'; 
                //contentHTML += '<div class="olLayerGeoRSSTitle">';
                //if (link) {
                //    contentHTML += '<a class="link" href="'+link+'" target="_blank">'+nr+'</a>';
                //} 
                //contentHTML += '</div>';
                // contentHTML += '<div style="" class="olLayerGeoRSSDescription">';
                contentHTML += description;
				
				//LIDELBUS 
				contentHTML += '<input type="button" style="width: 50%; margin-top:10px;" value="as Start" onclick="asStart();"><input type="button" style="width: 50%; margin-top:10px;" value="as Destination" onclick="asStop();">';
                contentHTML += '</div>';
				
				//LIDELBUS: Parsing the Name of the Stop
				clickedMarkerDescription = description;
				// clickedMarkerDescription = clickedMarkerDescription.replace("<br> StopName: ","");
				clickedMarkerDescription = clickedMarkerDescription.replace("<br>","");
				clickedMarkerDescription = clickedMarkerDescription.substring(1,clickedMarkerDescription.length);

				
                data['popupContentHTML'] = contentHTML;                
            }
            			            
            feature.popup=popup = new OpenLayers.Popup(null,
                   new OpenLayers.LonLat(feature.geometry.x,feature.geometry.y),
                   data.popupSize,contentHTML
                   //,true
            );
           
           
           feature.data=data;
         
		var popup = this.popup;
		OpenLayers.Event.observe(popup.div, "click",
			OpenLayers.Function.bind(function() { 
				for(var i=0; i < this.layer.map.popups.length; i++) { 
					this.layer.map.removePopup(this.layer.map.popups[i]); 
				}
			}, this)
		);
		this.layer.map.addPopup(popup);
         
        OpenLayers.Event.stop(evt);
    },
	
	
    /**
     * Method: clearFeatures
     * Destroy all features in this layer.
     */
    clearFeatures: function() {
        if (this.features != null) {
            while(this.features.length > 0) {
                var feature = this.features[0];
                OpenLayers.Util.removeItem(this.features, feature);
                feature.destroy();
            }
        }        
    },
    
    CLASS_NAME: "GeoRdfLayer"
});

